package com.proton.carepatchtemp.fragment.dialogfragment;


import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.database.TestManager;
import com.proton.carepatchtemp.ui.FlowLayout;
import com.proton.carepatchtemp.utils.eventbus.MainBusListener;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.ReportCenter;
import com.proton.carepatchtemp.utils.ui.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AddNoteDialogFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AddNoteDialogFragment extends DialogFragment implements MainBusListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String deviceAddress;
    private String reportID;
    private View view;
    /**
     * 药物治疗
     */
    private TextView mTvDrugTreatment;
    /**
     * 物理治疗
     */
    private TextView mTvPhysicalTherapy;
    /**
     * 宝宝状态
     */
    private TextView mTvPhysicalCondition;
    private FlowLayout mFlowLayout;
    /**
     * 您的宝宝服用过哪些药物？
     */
    private EditText mEtNoteContent;
    /**
     * 保存
     */
    private TextView mTvSaveNote;
    private ImageView mIvClose;
    /**
     * 显示的文字
     */
    private String[] mDatas = new String[]{
            VCare.get().getString(R.string.note_drug_ibuprofen),
            VCare.get().getString(R.string.note_drug_paracetamol),
            VCare.get().getString(R.string.note_drug_dextro_ibuprofen_suppository),
            VCare.get().getString(R.string.note_drug_999_cold_medicine)};
    private int type = 1;

    public AddNoteDialogFragment() {
        initBus();
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param deviceAddress Parameter 1.
     * @param reportId      Parameter 2.
     * @return A new instance of fragment AddNoteDialogFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AddNoteDialogFragment newInstance(String deviceAddress, String reportId) {
        AddNoteDialogFragment fragment = new AddNoteDialogFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, deviceAddress);
        args.putString(ARG_PARAM2, reportId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
        if (getArguments() != null) {
            deviceAddress = getArguments().getString(ARG_PARAM1);
            reportID = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width2 = outMetrics.widthPixels;
        int height2 = outMetrics.heightPixels;

        Window dialogWindow = getDialog().getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.RIGHT);
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        lp.x = 0;
        lp.y = 0;
        lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialogWindow.setAttributes(lp);
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_add_note_dialog, container, false);
        initView(view);
        setListener();
        addView2FlowLayout();
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegisterEventBus();
    }

    public void setListener() {

        mIvClose.setOnClickListener(v -> {
            dismiss();
        });

        mTvDrugTreatment.setOnClickListener(view -> {
            if (type == 1) {
                return;
            }

            mEtNoteContent.setHint(R.string.notes_hint_drug);
            mTvDrugTreatment.setTextSize(18);
            mTvPhysicalTherapy.setTextSize(14);
            mTvPhysicalCondition.setTextSize(14);
            mTvDrugTreatment.setTextColor(ContextCompat.getColor(getActivity(), R.color.blueDeep));
            mTvPhysicalTherapy.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray));
            mTvPhysicalCondition.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray));
            type = 1;
            mDatas = new String[]{
                    VCare.get().getString(R.string.note_drug_ibuprofen),
                    VCare.get().getString(R.string.note_drug_paracetamol),
                    VCare.get().getString(R.string.note_drug_dextro_ibuprofen_suppository),
                    VCare.get().getString(R.string.note_drug_999_cold_medicine)
            };
            addView2FlowLayout();
        });

        mTvPhysicalTherapy.setOnClickListener(view -> {
            if (type == 2) {
                return;
            }
            mEtNoteContent.setHint(R.string.notes_hint_phyT);
            mTvDrugTreatment.setTextSize(14);
            mTvPhysicalTherapy.setTextSize(18);
            mTvPhysicalCondition.setTextSize(14);
            mTvDrugTreatment.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray));
            mTvPhysicalTherapy.setTextColor(ContextCompat.getColor(getActivity(), R.color.blueDeep));
            mTvPhysicalCondition.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray));
            type = 2;
            mDatas = new String[]{
                    VCare.get().getString(R.string.note_phy_ice_bag),
                    VCare.get().getString(R.string.note_phy_warm_bath),
                    VCare.get().getString(R.string.note_phy_alcohol_sponge_bath),
                    VCare.get().getString(R.string.note_phy_feet_in_warm_water),
                    VCare.get().getString(R.string.note_phy_cooling_gel),
                    VCare.get().getString(R.string.note_phy_drink_water)
            };
            addView2FlowLayout();
        });

        mTvPhysicalCondition.setOnClickListener(view -> {
            if (type == 3) {
                return;
            }
            mEtNoteContent.setHint(R.string.notes_hint_phyC);
            mTvDrugTreatment.setTextSize(14);
            mTvPhysicalTherapy.setTextSize(14);
            mTvPhysicalCondition.setTextSize(18);
            mTvDrugTreatment.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray));
            mTvPhysicalTherapy.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray));
            mTvPhysicalCondition.setTextColor(ContextCompat.getColor(getActivity(), R.color.blueDeep));
            type = 3;
            mDatas = new String[]{
                    VCare.get().getString(R.string.note_con_coughed),
                    VCare.get().getString(R.string.note_con_dehydrated),
                    VCare.get().getString(R.string.note_con_twitchy),
                    VCare.get().getString(R.string.note_con_unconcious),
                    VCare.get().getString(R.string.note_con_general_weakness),
                    VCare.get().getString(R.string.note_con_lethargic),
                    VCare.get().getString(R.string.note_con_diarrheic),
                    VCare.get().getString(R.string.note_con_vomitive),
                    VCare.get().getString(R.string.note_con_snotty),
                    VCare.get().getString(R.string.note_con_inappetent),
                    VCare.get().getString(R.string.note_con_crying),
                    VCare.get().getString(R.string.note_con_cold_limbs)
            };
            addView2FlowLayout();
        });

        mTvSaveNote.setOnClickListener(view -> {
            if (!TextUtils.isEmpty(mEtNoteContent.getText())) {
                ReportCenter.addComment(reportID + "", type, mEtNoteContent.getText().toString());
            } else {
                ToastUtils.w(R.string.content_not_empty);
            }
        });
    }

    private void addView2FlowLayout() {
        mFlowLayout.removeAllViews();
        for (int i = 0; i < mDatas.length; i++) {
            final TextView view = new TextView(getActivity());
            view.setText(mDatas[i]);
            view.setTextColor(Color.WHITE);
            view.setPadding(5, 5, 5, 5);
            view.setGravity(Gravity.CENTER);
            view.setTextSize(14);

            Random random = new Random();
            // 设置点击事件
            view.setOnClickListener(v -> {
                mEtNoteContent.append(view.getText() + ";");
            });

            // 设置彩色背景
            GradientDrawable normalDrawable = new GradientDrawable();
            normalDrawable.setShape(GradientDrawable.RECTANGLE);
            normalDrawable.setCornerRadii(new float[]{8F, 8F, 8F, 8F, 8F, 8F, 8F, 8F});
            int a = 255;
            int r = 50 + random.nextInt(150);
            int g = 50 + random.nextInt(150);
            int b = 50 + random.nextInt(150);
            normalDrawable.setColor(Color.argb(a, r, g, b));

            // 设置按下的灰色背景
            GradientDrawable pressedDrawable = new GradientDrawable();
            pressedDrawable.setShape(GradientDrawable.RECTANGLE);
            pressedDrawable.setColor(Color.GRAY);
            pressedDrawable.setCornerRadii(new float[]{8F, 8F, 8F, 8F, 8F, 8F, 8F, 8F});
            // 背景选择器
            StateListDrawable stateDrawable = new StateListDrawable();
            stateDrawable.addState(new int[]{android.R.attr.state_pressed}, pressedDrawable);
            stateDrawable.addState(new int[]{}, normalDrawable);

            // 设置背景选择器到TextView上
            view.setBackground(stateDrawable);

            mFlowLayout.addView(view);
        }
    }

    private void initView(View view) {
        mTvDrugTreatment = view.findViewById(R.id.tv_drug_treatment);
        mTvPhysicalTherapy = view.findViewById(R.id.tv_physical_therapy);
        mTvPhysicalCondition = view.findViewById(R.id.tv_physical_condition);
        mFlowLayout = view.findViewById(R.id.flow_layout);
        mEtNoteContent = view.findViewById(R.id.et_note_content);
        mTvSaveNote = view.findViewById(R.id.tv_save_note);
        mIvClose = view.findViewById(R.id.iv_close);
    }

    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.REPORT_ADD_NOTE:
                mEtNoteContent.setText("");
                TestManager.addNotePoint(deviceAddress, type, System.currentTimeMillis());
                ToastUtils.s(R.string.add_note_success);
                AddNoteDialogFragment.this.dismiss();
                break;
            default:
                break;
        }
    }

    public void initBus() {
       /* if(new EventBus().isRegistered(this)){
            EventBus.getDefault().register(BaseFragment.this);
        }*/
        EventBus.getDefault().register(AddNoteDialogFragment.this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dealOnEvent(MainEvent event) {
        if (canDeal(event)) {
            try {
                dealEvent(event);
            } catch (Throwable e) {
                LogUtils.e(e);
            }
        }
    }

    public boolean canDeal(MainEvent event) {
        return event != null && getActivity() != null && !getActivity().isFinishing();
    }

    public void unRegisterEventBus() {
        EventBus.getDefault().unregister(AddNoteDialogFragment.this);
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }
}
